package com.cargohu.aishouyu.member.service.impl;

import com.cargohu.aishouyu.framework.exception.BusinessException;
import com.cargohu.aishouyu.framework.page.OrderByItem;
import com.cargohu.aishouyu.framework.page.Paging;
import com.cargohu.aishouyu.framework.service.impl.BaseServiceImpl;
import com.cargohu.aishouyu.member.dto.ChatHistoryAddDTO;
import com.cargohu.aishouyu.member.dto.ChatHistoryUpdateDTO;
import com.cargohu.aishouyu.member.entity.ChatHistory;
import com.cargohu.aishouyu.member.mapper.ChatHistoryMapper;
import com.cargohu.aishouyu.member.req.ChatHistoryRequest;
import com.cargohu.aishouyu.member.resp.ChatHistoryDetailVo;
import com.cargohu.aishouyu.member.resp.ChatHistoryResponse;
import com.cargohu.aishouyu.member.service.ChatHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 聊天记录 服务实现类
 *
 * @author aaron.wang
 * @since 2023-11-27
 */
@Slf4j
@Service
public class ChatHistoryServiceImpl extends BaseServiceImpl<ChatHistoryMapper, ChatHistory> implements ChatHistoryService {

    @Autowired
    private ChatHistoryMapper chatHistoryMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addChatHistory(ChatHistoryAddDTO chatHistoryAddDTO) throws Exception {
        ChatHistory chatHistory = new ChatHistory();
        BeanUtils.copyProperties(chatHistoryAddDTO, chatHistory);
        chatHistory.setTime(new Date());
        return save(chatHistory);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateChatHistory(ChatHistoryUpdateDTO chatHistoryUpdateDTO) throws Exception {
        Long id = chatHistoryUpdateDTO.getId();
        ChatHistory chatHistory = getById(id);
        if (chatHistory == null) {
            throw new BusinessException("聊天记录不存在");
        }
        BeanUtils.copyProperties(chatHistoryUpdateDTO, chatHistory);
        return updateById(chatHistory);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteChatHistory(Long id) throws Exception {
        return removeById(id);
    }

    @Override
    public ChatHistoryDetailVo getChatHistoryById(Long id) throws Exception {
        return chatHistoryMapper.getChatHistoryById(id);
    }

    @Override
    public Paging<ChatHistoryResponse> getChatHistoryList(ChatHistoryRequest chatHistoryRequest) throws Exception {
        handlePage(chatHistoryRequest, OrderByItem.desc("id"));
        List<ChatHistoryResponse> list = chatHistoryMapper.getChatHistoryList(chatHistoryRequest);
        Paging<ChatHistoryResponse> paging = new Paging<>(list);
        return paging;
    }

}
